import axios from 'axios';
import QS from 'qs'; 

axios.defaults.baseURL = "/api";

axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

// 添加请求拦截器
axios.interceptors.request.use(config => {
    // 在发送请求之前做些什么
    return config
}, error => {
    // 对请求错误做些什么
    return Promise.reject(error)
})

// 添加响应拦截器
axios.interceptors.response.use(response => {
    // 对响应数据做点什么
    return response
}, error => {
    // 对响应错误做点什么
    return Promise.reject(error)
});

/**
  * get方法，对应get请求
  * @param {String} url [请求的url地址]
  * @param {Object} params [请求时携带的参数]
  */
export function get(url, params) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            params: params
        }).then(res => {
            resolve(res.data);
        }).catch(err => {
            reject(err.data)
        })
    });
}

/**
  * post方法，对应post请求
  * @param {String} url [请求的url地址]
  * @param {Object} params [请求时携带的参数]
  */
export function post(url, params) {
    return new Promise((resolve, reject) => {
          axios.post(url, QS.stringify(params))
        .then(res => {
            resolve(res.data);
        })
        .catch(err =>{
            reject(err.data)
        })
    });
}

/**
 * 上传文件
 * @param {*} url 
 * @param {*} formData 
 */
export function uploadFile(url, formData) {
    return new Promise((resolve, reject) => {
        axios.post(url, formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(response => {
            resolve(response)
        }).catch(error => {
            console.log("上传失败", error);
        })
    });
}

/**
 *  下载文件
 *  示例: http://localhost:8080/download?fileId=20250613113436
 * @param {} url 
 */
export function downloadFile(url) {
    return new Promise((resolve, reject) => {
        axios.get(url, {
            responseType: 'blob',
        }).then(res => {
            let contentDisposition  = res.headers['content-disposition'];
            const patt = new RegExp('filename=([^;]+\\.[^\\.;]+);*')
            const result = patt.exec(contentDisposition)
            const filename = decodeURI(result[1]) // 处理文件名,解决中文乱码问题
            let blob = new Blob([res.data], {type: 'application/octet-stream'});
            let url = window.URL.createObjectURL(blob);
            let a = document.createElement('a');
            a.href = url;
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(url);
            a.remove();
            resolve();
        })
    });
}
